//
//  JUFNRefreashControl.swift
//  WiBoPM
//
//  Created by 陈俊峰 on 2017/1/12.
//  Copyright © 2017年 陈俊峰. All rights reserved.
//

import UIKit

enum RefreshStatus:Int {
    case Normal
    case Already
    case Refreashing
}

let refreshHeight : CGFloat = 60

class JUFNRefreashControl: UIControl {
    
    var currentStatus:RefreshStatus = .Normal{
        didSet{
            switch currentStatus {
            case .Normal:
                arrowImgV.isHidden = false
                activityIndicatorView.stopAnimating()
                
                tipLabel.text = "下拉刷新"
                UIView.animate(withDuration: 0.25, animations: {
                    self.arrowImgV.transform = CGAffineTransform.identity
                })
                
                if oldValue == .Refreashing{
                    //这里把导航栏驻留停止
                    UIView.animate(withDuration: 0.25, animations: {
                        self.superScrollView?.contentInset.top = (self.superScrollView?.contentInset.top)! - refreshHeight
                    })
                }
            case .Already:
                tipLabel.text = "松开刷新"
                //这里把数据箭头
                UIView.animate(withDuration: 0.25, animations: {
                    self.arrowImgV.transform = CGAffineTransform.init(rotationAngle: CGFloat(M_PI))
                })
            case .Refreashing:
                tipLabel.text = "正在刷新"
                self.sendActions(for: .valueChanged)
                UIView.animate(withDuration: 0.25, animations: {
                    self.arrowImgV.isHidden = true
                    self.activityIndicatorView.startAnimating()
                })
                //达到悬停效果,这里做笔记.目的就是在刷新的状态有所驻留
                UIView.animate(withDuration: 0.25, animations: {
                    self.superScrollView?.contentInset.top = (self.superScrollView?.contentInset.top)! + refreshHeight
                })
                
            }
        }
    }
    
    override init(frame: CGRect) {
        let refreshRect = CGRect(x: 0, y: -refreshHeight, width: screenWidth, height: refreshHeight)
        super.init(frame: refreshRect)
        backgroundColor = UIColor.orange
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupUI() {
        addSubview(backgroundImageV)
        addSubview(tipLabel)
        addSubview(activityIndicatorView)
        addSubview(arrowImgV)
        
        //设置约束
        backgroundImageV.snp.makeConstraints { (make) in
            make.centerX.bottom.equalTo(self)
        }
        tipLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(self).offset(10)
            make.centerY.equalTo(self)
        }
        activityIndicatorView.snp.makeConstraints { (make) in
            make.centerY.equalTo(self)
            make.right.equalTo(tipLabel.snp.left).offset(-5)
        }
        arrowImgV.snp.makeConstraints { (make) in
            make.center.equalTo(activityIndicatorView)
        }
    }
    
    
    override func willMove(toSuperview newSuperview: UIView?) {
        
        let superView = newSuperview as! UIScrollView
        superScrollView = superView
        //这里使用kvo监听contentOffset变化
        superView.addObserver(self, forKeyPath: "contentOffset", options: [.new], context: nil)
    }
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        let contentOffsetY:CGFloat = (self.superScrollView?.contentOffset.y)!
        let divideValue:CGFloat = -124
        //根据偏移量,判断所处的状态
        //考虑需要切换状态的情况
        if (superScrollView?.isDragging)!{
            //1.正常状态->准备状态
            
            if currentStatus == .Normal&&contentOffsetY < divideValue {
                currentStatus = .Already
                print("准备")
            }else if currentStatus == .Already&&contentOffsetY > divideValue{
                //3.准备状态 ->正常状态
                currentStatus = .Normal
                print("正常")
            }
            
        }else{
            //2.准备状态->刷新状态
            if currentStatus == .Already {
                currentStatus = .Refreashing
                print("刷新")
            }
//            else if currentStatus == .Refreashing{
//                currentStatus = .Normal
//            }
        }
    }
    var superScrollView:UIScrollView?
    lazy var tipLabel:UILabel = UILabel.init(text: "下拉刷新", fontSize: 14, textColor: UIColor.darkGray)
    lazy var arrowImgV:UIImageView = UIImageView(image: #imageLiteral(resourceName: "tableview_pull_refresh"))
    
    lazy var activityIndicatorView:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    lazy var backgroundImageV:UIImageView = UIImageView(image: UIImage(named: "refreshbg"))
    
}
